<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="f"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!-- CONTENT -->
<!--TITLE -->
<div class="row">
	<div id="paper-top">
		<div class="col-sm-12">
			<!-- TITULO DA PÁGINA -->
			<h2 class="tittle-content-header">
				<i class="icon-menu"></i> <span>Editar Atendimento</span>
			</h2>
		</div>
	</div>
</div>
<!--/ TITLE -->

<!-- BREADCRUMB -->
<ul id="breadcrumb">
	<li><span class="entypo-home"></span></li>
	<li><i class="fa fa-lg fa-angle-right"></i></li>
	<li><a href="#" title="Sample page 1">Página Inicial</a></li>
	<li><i class="fa fa-lg fa-angle-right"></i></li>
	<li><a href="#" title="Sample page 1">Editar Atendimento</a></li>
</ul>
<!-- FIM BREADCRUMB -->

<div class="fluida">

	<div class="content-wrap margin-bottom">
		<div class="row-cols novo-atendimento">

			<div class="rows">

				<c:if test="${validator}">
					<div class="alert alert-danger">
						<button data-dismiss="alert" class="close" type="button">×</button>
						<span class="entypo-attention"></span> <strong>Opa!</strong>&nbsp;&nbsp;Houve
						algum erro na hora de salvar os seguintes dados:
						<ul>
							<c:forEach items="${errors}" var="e">
								<li><c:out value="${e}" /></li>
							</c:forEach>
						</ul>
					</div>
				</c:if>

				<f:form id="transition-duration-demo" class="transition-form" method="post"
				 action="mergeService" modelAttribute="serviceModify">

				

					<fieldset class="row-cols margin-bottom fluida"
						title="Dados do Cliente">
						<legend>&nbsp;&nbsp;</legend>

						<!-- Anotações -->
						<div class="col-sm-4 pull-right">
							<div class="nest text margin-bottom">

								<div class="title-alt">
									<h6>
										<a href="#" rel="obs-note" class="toggle-box">Anotações</a>
									</h6>
									<a href="#" rel="obs-note" class="icon-chevron-down toggle-box"></a>
								</div>

								<div class="body-nest" id="obs-note" style="display: none;">
									<div class="aling-form">
										<div class="box03">
											<f:textarea rows="5" cols="5"  path="observations"
												class="form-control" style="min-height:130px;"></f:textarea>
										</div>
									</div>
								</div>

							</div>
						</div>


						<div class="col-sm-8">

							<!-- Dados Básicos -->
							<div class="nest text margin-bottom">
								<div class="title-alt">
									<h6>Dados Básicos</h6>
								</div>

								<div class="body-nest">

									<div class="aling-form">

										<div class="box01">
											<f:input id="first-name" placeholder="Primeiro Nome"
												path="firstName" type="text" class="form-control" />
										</div>

										<div class="box02">
											<f:input id="last-name" placeholder="Sobrenome"
												path="lastName" type="text" class="form-control" />
										</div>

										<div class="box01">
											<div class="input-group ">
												<span class="input-group-addon btn-success"><i
													class="fa fontawesome-envelope-alt"></i></span>
												<f:input id="email" placeholder="E-mail" path="email"
													type="text" class="form-control" />
											</div>
										</div>

										<div class="box02">
											<div class="input-group ">
												<span class="input-group-addon btn-success"><i
													class="fa fa-phone-square"></i></span>
												<f:input id="residential-phone"
													placeholder="Telefone Residencial"
													path="customerPhone.homePhone" type="text"
													class="form-control" />
											</div>
										</div>

										<div class="box01">
											<div class="input-group ">
												<span class="input-group-addon btn-success"><i
													class="fa entypo-mobile"></i></span>
												<f:input id="mobile-telefone" placeholder="Telefone Celular"
													path="customerPhone.celPhone" type="text"
													class="form-control" />
											</div>
										</div>

										<div class="box02">
											<div class="input-group ">
												<span class="input-group-addon btn-success"><i
													class="fa fa-phone-square"></i></span>
												<f:input id="work-telephone"
													placeholder="Telefone comercial"
													path="customerPhone.workPhone" type="text"
													class="form-control" />
											</div>
										</div>

										<div class="box01">
											<div class="input-group ">
												<span class="input-group-addon btn-success"><i
													class="fa fa-calendar"></i></span>
												<f:input id="birthday" placeholder="Data de Nascimento"
													path="birthDate" type="text" class="form-control" />
											</div>
										</div>

										<div class="box02 skin skin-flat">
											<div class="box-radio">
												<f:radiobutton id="gender-male" path="gender" value="M" />
												<label for="line-radio-1">Masculino</label>
											</div>

											<div class="box-radio">
												<f:radiobutton id="gender-female" path="gender" value="F" />
												<label for="line-radio-2">Feminino</label>
											</div>
										</div>

									</div>



								</div>
							</div>

							<!-- Dados Complementares -->
							<div class="nest text margin-bottom">

								<div class="title-alt">
									<h6>
										<a href="#" rel="dados-complementares" class="toggle-box">Dados
											Complementares</a>
									</h6>
									<a href="#" rel="dados-complementares"
										class="icon-chevron-down toggle-box"></a>
								</div>

								<div class="body-nest" id="dados-complementares"
									style="display: none;">

									<div class="aling-form">

										<div class="box01">
											<f:input id="cpf" placeholder="CPF ou CNPJ"
												path="document.cpf" type="text" class="form-control" />
										</div>

										<div class="box02">
											<f:input id="rg" placeholder="RG" path="document.rg"
												type="text" class="form-control" />
										</div>



										<div class="box01">
											<f:input id="cep" placeholder="CEP"
												path="customerAddress.cep" type="text" class="form-control" />
										</div>

										<div class="box02">
											<f:input id="estado" placeholder="UF"
												path="customerAddress.state" type="text"
												class="form-control" />
										</div>

										<div class="box01">
											<f:input id="cidade" placeholder="Cidade"
												path="customerAddress.city" type="text" class="form-control" />
										</div>

										<div class="box02">
											<f:input id="bairro" placeholder="Bairro"
												path="customerAddress.quarter" type="text"
												class="form-control" />
										</div>

										<div class="box01">
											<f:input id="endereco" placeholder="Rua"
												path="customerAddress.street" type="text"
												class="form-control" />
										</div>

										<div class="box02">
											<f:input id="numero" placeholder="Número"
												path="customerAddress.number" type="text"
												class="form-control" />
										</div>

										<div class="box01">
											<f:input id="complemento" placeholder="Complemento"
												path="customerAddress.complement" type="text"
												class="form-control" />
										</div>
									</div>

								</div>

							</div>

							<!-- List de Passageiros -->
							<div class="nest text margin-bottom">

								<div class="title-alt">
									<h6>
										<a href="#" rel="list-passageiros" class="toggle-box">Cadastro
											de Passageiros</a>
									</h6>
									<a href="#" rel="list-passageiros"
										class="icon-chevron-down toggle-box"></a>
								</div>

								<div class="body-nest" id="list-passageiros"
									style="display: none;">

									<div class="aling-form">

										<div class="box03">
											<a class="btn btn-primary btn-lg" data-toggle="modal"
												data-backdrop="static" data-target="#myModal"><span
												class="entypo-plus-squared"></span>&nbsp;&nbsp;Cadastrar
												Novo Passageiro</a>
										</div>




										<ul id="passenger-list" class="list-user">


										</ul>

									</div>

								</div>

							</div>

						</div>


					</fieldset>

					<fieldset class="row-cols margin-bottom"
						title="Detalhes do Atendimento">
						<legend>&nbsp;&nbsp;</legend>

						<!-- Quem vai nesta viagem -->
						<div class="col-sm-4 pull-right">
							<div class="nest text margin-bottom">

								<div class="title-alt">
									<h6>
										<a href="#" rel="quem-vai" class="toggle-box">Quem vai
											nesta viagem?</a>
									</h6>
									<a href="#" rel="quem-vai" class="icon-chevron-down toggle-box"></a>
								</div>

								<div class="body-nest" id="quem-vai">

									<div id="passenger-list-confirmation"
										class="aling-form skin skin-flat">

										<div id="passenger-alone" class="alert alert-info box03">
											<span class="entypo-info-circled"></span> <b>Parece que o
												cliente irá viajar sozinho</b>.
										</div>

									</div>
								</div>

							</div>
						</div>

						<!-- Destinos Oferecidos -->
						<div class="col-sm-8">
							<div class="nest text margin-bottom">

								<div class="title-alt">
									<h6>
										<a href="#" rel="destino-solicitado" class="toggle-box">Negociar
											Destinos</a>
									</h6>
									<a href="#" rel="destino-solicitado"
										class="icon-chevron-down toggle-box"></a>
								</div>

								<div class="body-nest" id="destino-solicitado">

									<div class="aling-form">
									
										<div class="box03">
											<a class="btn btn-primary btn-lg" data-toggle="modal"
												data-backdrop="static" data-target="#destinationModal"><span
												class="entypo-plus-squared"></span>&nbsp;&nbsp;Adicionar um
												Destino</a>
										</div>										
										<ul id="destination-list" class="list-user">
											<c:forEach items="${destinationNegotiated}" var="name">
												<ul class="list-user">
													<li><b>${name}</b></li>
												</ul>
											</c:forEach>

										</ul>
									</div>
								</div>

							</div>
						</div>


						<!-- Hístórico de Destino deste passageiro -->
						<div class="col-sm-8">
							<div class="nest text margin-bottom">

								<div class="title-alt">
									<h6>
										<a href="#" rel="destino-historico" class="toggle-box">Hístórico
											de Destino deste passageiro</a>
									</h6>
									<a href="#" rel="destino-historico"
										class="icon-chevron-down toggle-box"></a>
								</div>

								<div class="body-nest" id="destino-historico"
									style="display: none">

									<div class="aling-form">
										<c:choose>
											<c:when test="${!empty historyList}">
												<c:forEach items="${historyList}" var="hl">
													<ul class="list-user">
														<li><b>${hl.register}</b></li>

													</ul>
												</c:forEach>
											</c:when>
											<c:otherwise>
												<div class="alert alert-info">
													<span class="entypo-info-circled"></span> <strong>Não
														há registro historico deste atendimento!!</strong>
												</div>
											</c:otherwise>
										</c:choose>


									</div>
								</div>

							</div>
						</div>

					</fieldset>

					<button id="submit-all" type="submit"
						class="stepy-finish pull-right btn btn-info">Pronto!</button>
				</f:form>

				<!-- Modal Passageiros-->
				<div class="modal fade" id="myModal" role="dialog"
					aria-labelledby="myModalLabel" aria-hidden="true">
					<div class="modal-dialog">

						<div class="modal-content">
							<form id="modal-form" action="./addPassenger" method="post">
								<div class="modal-header">
									<button type="button" class="close" data-dismiss="modal">
										<span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
									</button>
									<h4 class="modal-title" id="myModalLabel">Cadastrar Novo
										Passageiro</h4>
								</div>
								<div class="modal-body">

									<div id="div-modal-input-body"
										class="aling-form col-sm-12 nest text"
										style="padding-top: 25px">

										<div class="box01">
											<select id="familyBond" class="form-control"
												name="familyBond">
												<c:forEach items="${listOfBondNames}" var="bond">
													<option value="${bond.key}">${bond.value}</option>
												</c:forEach>
											</select>
										</div>

										<div class="box02">

											<input id="passenger-name" placeholder="Nome do Passageiro"
												name="firstName" type="text" class="form-control" />
										</div>

										<div class="box01">

											<input id="passenger-lastName"
												placeholder="Sobrenome do Passageiro" type="text"
												name="lastName" class="form-control" />
										</div>

										<div class="box02">
											<div class="input-group ">
												<span class="input-group-addon btn-success"><i
													class="fa fontawesome-envelope-alt"></i></span> <input
													id="passenger-email" placeholder="E-mail" type="text"
													name="email" class="form-control" />
											</div>
										</div>

										<div class="box01">
											<div class="input-group ">
												<span class="input-group-addon btn-success"><i
													class="fa fa-phone-square"></i></span> <input id="passenger-phone"
													placeholder="Telefone Principal" type="text" name="mainTel"
													class="form-control" />
											</div>
										</div>

										<div class="box02">
											<div class="input-group ">
												<span class="input-group-addon btn-success"><i
													class="fa fa-calendar"></i></span> <input id="passenger-birth"
													placeholder="Data de Nascimento" type="text"
													name="birthDate" class="form-control" />
											</div>
										</div>

										<div class="box01">
											<input id="passenger-rg" placeholder="RG" type="text"
												name="documentPassenger.rg" class="form-control"
												style="margin: 0px;" />
										</div>

										<div class="box02">
											<input id="passenger-cpf" placeholder="CPF" type="text"
												name="documentPassenger.cpf" class="form-control" />
										</div>
										<input type="hidden" name="${_csrf.parameterName}"
											value="${_csrf.token}" />

									</div>

								</div>
								<div class="modal-footer clear" style="margin: 0px;">
									<button type="button" class="btn btn-danger"
										data-dismiss="modal">Cancelar</button>
									<button id="buttton-modal-register " type="submit"
										class="btn btn-primary">Cadastrar</button>
								</div>
							</form>
						</div>
					</div>
				</div>
				
				<!-- Modal Editar Passageiros-->
				<div class="modal fade" id="myPassengerEdit" role="dialog"
					aria-labelledby="myModalLabel" aria-hidden="true">
					<div class="modal-dialog">

						<div class="modal-content">
							<form id="modal-form">
								<div class="modal-header">
									<button type="button" class="close" data-dismiss="modal">
										<span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
									</button>
									<h4 class="modal-title" id="myModalLabel">Editar
										Passageiro</h4>
								</div>
								<div class="modal-body">

									<div id="div-modal-input-body"
										class="aling-form col-sm-12 nest text"
										style="padding-top: 25px">

										<div class="box01">
											<select id="familyBond" class="form-control"
												name="familyBond">
												<c:forEach items="${listOfBondNames}" var="bond">
													<option value="${bond.key}">${bond.value}</option>
												</c:forEach>
											</select>
										</div>

										<div class="box02">

											<input id="passenger-name" placeholder="Nome do Passageiro"
												name="firstName" type="text" class="form-control" />
										</div>

										<div class="box01">

											<input id="passenger-lastName"
												placeholder="Sobrenome do Passageiro" type="text"
												name="lastName" class="form-control" />
										</div>

										<div class="box02">
											<div class="input-group ">
												<span class="input-group-addon btn-success"><i
													class="fa fontawesome-envelope-alt"></i></span> <input
													id="passenger-email" placeholder="E-mail" type="text"
													name="email" class="form-control" />
											</div>
										</div>

										<div class="box01">
											<div class="input-group ">
												<span class="input-group-addon btn-success"><i
													class="fa fa-phone-square"></i></span> <input id="passenger-phone"
													placeholder="Telefone Principal" type="text" name="mainTel"
													class="form-control" />
											</div>
										</div>

										<div class="box02">
											<div class="input-group ">
												<span class="input-group-addon btn-success"><i
													class="fa fa-calendar"></i></span> <input id="passenger-birth"
													placeholder="Data de Nascimento" type="text"
													name="birthDate" class="form-control" />
											</div>
										</div>

										<div class="box01">
											<input id="passenger-rg" placeholder="RG" type="text"
												name="documentPassenger.rg" class="form-control"
												style="margin: 0px;" />
										</div>

										<div class="box02">
											<input id="passenger-cpf" placeholder="CPF" type="text"
												name="documentPassenger.cpf" class="form-control" />
										</div>
										<input type="hidden" name="${_csrf.parameterName}"
											value="${_csrf.token}" />

									</div>

								</div>
								<div class="modal-footer clear" style="margin: 0px;">
									<button type="button" class="btn btn-danger"
										data-dismiss="modal">Cancelar</button>
									<button id="buttton-modal-register " type="submit"
										class="btn btn-primary">Cadastrar</button>
								</div>
							</form>
						</div>
					</div>
				</div>
				


				<!-- Modal Novo Destino Requisitado-->
				<div class="modal fade" id="destinationModal" role="dialog"
					aria-labelledby="myModalLabelDestination" aria-hidden="true">
					<div class="modal-dialog">

						<div class="modal-content">
							<form id="destination-modal-form">

								<div class="modal-header">
									<button type="button" class="close" data-dismiss="modal">
										<span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
									</button>
									<h4 class="modal-title" id="myModalLabelDestination">Negociar Novo
										Destino</h4>
								</div>

								<div class="modal-body">

									<div id="div-modal-input-body-destination"
										class="aling-form col-sm-12 nest text"
										style="padding-top: 25px">
										<c:if test="${updateError}">
										<div class="alert alert-danger">
											<span class="entypo-attention"></span>Você
												precisa preencher todos os campos ou inserirum intervalo de datas
												compatíveis!
										</div>
										</c:if>
										<div class="box01">
											<select id="destination-passenger-list" class="form-control" name="${customerService.serviceItem.destination}">
												<c:forEach items="${destinationList}" var="destination">
													<option value="${destination.idDestination}">${destination.dtName}</option>
												</c:forEach>
											</select>
										</div>

										<div class="box02">
											<div class="input-group skin skin-flat">
												<input id="ckb-requested" type="checkbox" name="${customerService.serviceItem.requestedDestination}" /> <label
													id="ckb-label" for="ckb-requested">Destino
													Solicitado pelo Passageiro?</label>

											</div>
										</div>

										<div class="box01">
											<div class="input-group ">
												<span id="span-departure"
													class="input-group-addon btn-success"><i
													class="fa fa-calendar"></i></span> <input id="input-departure"
													type="text"
													name="${customerService.serviceItem.departureDate}"
													class="form-control" placeholder="Data de Ida" />
											</div>
										</div>

										<div class="box02">
											<div class="input-group ">
												<span id="span-arrive" class="input-group-addon btn-success"><i
													class="fa fa-calendar"></i></span> <input id="input-arrive"
													type="text"
													name="${customerService.serviceItem.arrivalDate}"
													class="form-control" placeholder="Data de Volta" />
											</div>
										</div>

										<div class="box01">
											<select id="combo-saleType" class="form-control" name="${customerService.serviceItem.saleType}">
												<c:forEach items="${listOfSaleTypes}" var="saleType">
													<option value="${saleType.key}">${saleType.value}</option>
												</c:forEach>
											</select>
										</div>

										<div class="box02">
											<div class="input-group ">
												<span
													class="input-group-addon btn-success"><i
													class="fa fa-money"></i></span> <input id="input-price"
													type="text" data-thousands="." data-decimal=","
													name="${customerService.serviceItem.valueNegotiated}"
													class="form-control" />
											</div>
										</div>


										<div class="box03">
											<textarea id="destination-observations" name="${customerService.serviceItem.negociationObservations}" rows="3" placeholder="Observações..." class="form-control"
												style="min-height: 130px;"></textarea>
										</div>


										<input type="hidden" name="${_csrf.parameterName}"
											value="${_csrf.token}" />

									</div>

								</div>
								<div class="modal-footer clear" style="margin: 0px;">
									<button type="button" class="btn btn-danger"
										data-dismiss="modal">Cancelar</button>
									<button id="button-add-destination" type="submit"
										class="btn btn-primary">Cadastrar</button>
								</div>
							</form>
						</div>
					</div>
				</div>
				
    			<!-- Modal Edidar Destino Requisitado-->
                <div class="modal fade" id="EditDestinationModal" role="dialog" aria-labelledby="myModalLabelDestination" aria-hidden="true">
                 <div class="modal-dialog">
                        <div class="modal-content">
                            <form id="destination-edit-form">

                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal">class="list-user"
                                        <span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
                                    </button>
                                    <h4 class="modal-title" id="myModalLabelDestination">Editar Novo
                                        Destino</h4>
                                </div>

                                <div class="modal-body">

									<div id="div-modal-input-body-destination"
                                        class="aling-form col-sm-12 nest text"
                                        style="padding-top: 25px">
                                        <c:if test="${updateError}">
										<div class="alert alert-danger">
											<span class="entypo-attention"></span>Você precisa preencher
											todos os campos ou inserir um intervalo de datas compatíveis!
										</div>
										</c:if>

										<div class="box01">
                                            <select id="edit-destination-passenger-list" class="form-control" name="${customerService.serviceItem.destination}">
                                                <c:forEach items="${destinationList}" var="destination">
                                                    <option value="${destination.idDestination}">${destination.dtName}</option>
                                                </c:forEach>
                                            </select>
                                        </div>

                                        <div class="box02">
                                            <div class="input-group skin skin-flat">
                                                <input id="edit-ckb-requested" type="checkbox" name="${customerService.serviceItem.requestedDestination}" /> <label
                                                    id="ckb-label" for="edit-ckb-requested">Destino
                                                    Solicitado pelo Passageiro?</label>

                                            </div>
                                        </div>

                                        <div class="box01">
                                            <div class="input-group ">
                                                <span id="span-departure"
                                                    class="input-group-addon btn-success"><i
                                                    class="fa fa-calendar"></i></span> <input id="edit-input-departure"
                                                    type="text"
                                                    name="${customerService.serviceItem.departureDate}"
                                                    class="form-control" placeholder="Data de Ida" />
                                            </div>
                                        </div>

                                        <div class="box02">
                                            <div class="input-group ">
                                                <span id="span-arrive" class="input-group-addon btn-success"><i
                                                    class="fa fa-calendar"></i></span> <input id="edit-input-arrive"
                                                    type="text"
                                                    name="${customerService.serviceItem.arrivalDate}"
                                                    class="form-control" placeholder="Data de Volta" />
                                            </div>
                                        </div>

                                        <div class="box01">
                                            <select id="edit-combo-saleType" class="form-control" name="${customerService.serviceItem.saleType}">
                                                <c:forEach items="${listOfSaleTypes}" var="saleType">
                                                    <option value="${saleType.key}">${saleType.value}</option>
                                                </c:forEach>
                                            </select>
                                        </div>

                                        <div class="box02">
                                            <div class="input-group ">
                                                <span
                                                    class="input-group-addon btn-success"><i
                                                    class="fa fa-money"></i></span> <input id="edit-input-price"
                                                    type="text" data-thousands="." data-decimal=","
                                                    name="${customerService.serviceItem.valueNegotiated}"
                                                    class="form-control" />
                                            </div>
                                        </div>


                                        <div class="box03">
                                            <textarea id="edit-destination-observations" name="${customerService.serviceItem.negociationObservations}" rows="3" placeholder="Observações..." class="form-control"
                                                style="min-height: 130px;"></textarea>
                                        </div>


                                        <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
                                        <input id="destinationid-hidden" type="hidden"/>

                                    </div>

                                </div>
                                <div class="modal-footer clear" style="margin: 0px;">
									<button id="button-update-destination" type="submit"
										class="btn btn-primary">Editar</button>
									<button type="button" class="btn btn-danger"
										data-dismiss="modal">Cancelar</button>

								</div>
                            </form>
                        </div>
                    </div>
                </div>
				
			</div>
		</div>
	</div>
</div>


<script type="text/javascript">

$('#div-modal-input-body-destination').on('click', '#input-departure', function (e){
	   $("#input-price").maskMoney(); 
	   $('#input-arrive').mask('99/99/9999');
	   $('#input-departure').mask('99/99/9999');
});

   $("#cep").change(function(){
      var cep_code = $(this).val();
      if( cep_code.length <= 0 ) return;
      $.get("http://cep.correiocontrol.com.br/"+cep_code+".json",
         function(result){
            if( result.erro ==true ){
               alert("CEP invalido!");
               return;
            }
            $("#cep").val( result.cep );
            $("#estado").val( result.uf );
            $("#cidade").val( result.localidade );
            $("#bairro").val( result.bairro );
            $("#endereco").val( result.logradouro );
            
         });
   });
   
   $('#modal-form').submit( function(e){
	   var url = "${pageContext.request.contextPath}/auth/addPassenger?${_csrf.parameterName}=${_csrf.token}";

	    $.ajax({
	           type: "POST",
	           url: url,
	           data: $("#modal-form").serialize(),
	           success: function(jsonData){
	        	   
	        	   if(jsonData != ""){
		        	    var passenger = jsonData.firstName;
			        	   
		        		$('#passenger-list').append('<li id="list-all-passenger" ><label>'+passenger+'</label></li>');
		        		
		        		$('#passenger-list li').each(function(i){
		        			 var button = $(this).find("button");
		        			if(! button.length){
		        				$(this).prepend('<button id="button-cancel-passenger" type="reset" class="btn btn-danger pull-right" style="position: relative; top: -1px;"><span class="entypo-cancel-squared"></span>&nbsp;&nbsp;Remover</button>');
		        			}
		                });
		        		
		        		if($('#passenger-alone').length){
		        			$('#passenger-alone').remove();
		        		}
		        		$('#passenger-list-confirmation').append('<div id="box03-passenger" class="box03"></div>');
		        		$('#box03-passenger').append('<input type="checkbox" id="ck"/>');
		        		$('#ck').after('<label for="ck">'+passenger+'</label>');
		        		

		        	    $('#myModal').modal('hide');
		        	    
		        	    $('#passenger-name').val('');
		        	    $('#passenger-lastName').val('');
		        	    $('#passenger-email').val('');
		        	    $('#passenger-phone').val('');
		        	    $('#passenger-birth').val('');
		        	    $('#passenger-rg').val('');
		        	    $('#passenger-cpf').val(''); 
	        	   }else{
	        		   if($('#div-error-passenger').length){
		        		   return false;
	        		   }else{
	        			   $('#div-modal-input-body').prepend('<div id="div-error-passenger" class="alert alert-info box03"></div>');
		        		   $('#div-error-passenger').append('<span id="span-error-passenger" class="entypo-info-circled"></span> <b>Você Precisa preencher no mínimo o nome e sobrenome do passageiro!</b>.');   
	        		   }

	        		  return false;
	        	   }
	           }
	         });

	    e.preventDefault();
   });
   
   $('#destination-modal-form').submit( function(e){
	   var departure =  $('#input-departure').val();
	   var arrive = $('#input-arrive').val();
	   var price = $('#input-price').val();
	   var saleType = $('#combo-saleType').val();
	   var destinationId = $('#destination-passenger-list').val();
	   var observations = $('#destination-observations').val();
	   var ckb = $('#ckb-requested').val();
	   
	   var url = "${pageContext.request.contextPath}/auth/addSelectedDestination?${_csrf.parameterName}=${_csrf.token}";
	   
	   $.ajax({
		type:'POST',
		data: {
			departure: departure,
			arrive: arrive,
			price: price,
			saletype: saleType,
			destinationId: destinationId,
			observations: observations,
			ckb: ckb
		},
		url: url,
		dataType: "json",
		success: function(jsonData){
			if (jsonData != null) {
        	    var destinationName = jsonData[0];
        	    var destinationId = jsonData[1];
	        	   
        		$('#destination-list').append('<li id="list-all-destination" ><label><b>'+destinationName+'</b></label></li>');
        		
        		$('#destination-list li').each(function(i){
        			 var button = $(this).find("button");
        			if(! button.length){
        				
        				$(this).prepend('<button id="edit-'+destinationId+'" type="button" data-toggle="modal" data-backdrop="static" data-target="#EditDestinationModal" class="btn btn-info pull-right" style="position: relative;"><span class="entypo-pencil"></span>&nbsp;&nbsp;Editar</button>');
                        $(this).prepend('<button id="cancel-'+destinationId+'" type="button" class="btn btn-danger pull-right" style="position: relative;><span class="entypo-cancel-squared"></span>&nbsp;&nbsp;Remover</button>');
        			}
                });
        		
        	    $('#destinationModal').modal('hide');
        	    
        		$('#input-departure').val('');
        		$('#input-arrive').val('');
        		$('#input-price').val('');
        		$('#combo-saleType').val('');
        		$('#destination-passenger-list').val('');
        		$('#destination-observations').val('');
        		$('#ckb-requested').val('');
        		
			} else {

			}
		}, 
		error: function(error){
			alert("Erro: Tente Novamente preenchendo todos os campos, ou entre em contato com o administrador do sistema.");
		}
	   });
	   e.preventDefault();
   });
   
   $("body").on("click", "#list-all-destination button.btn-danger", function (e) {
	    e.returnValue = false;
	    var dialog =  '<div id="dialog" <h1>Remover o destino selecionado?</h1></div>';
	    $('body').append(dialog);
	    var clickedID = this.id.split('-');
	    var destinationId = clickedID[1];
	    var url = "${pageContext.request.contextPath}/auth/deleteRequestedDestination/"+destinationId+"?${_csrf.parameterName}=${_csrf.token}";

	    var $li = $(this).closest('li');

	    $('#dialog').dialog({
	        resizable: false,
	        height: 140,
	        modal: true,
	        title: "Cancelar o Destino?",
	        buttons: {
	            "Sim": function () {
	                $(this).dialog("close");
	                $.ajax({
	                    type: "DELETE",
	                    url: url,
	                    dataType: "json",
	                    success: function (response) {
	                        $li.fadeOut(500, function () {
	                            $li.remove();
	                        });
	                    },
	                    error: function (xhr, ajaxOptions, thrownError) {
	                        //On error, we alert user
	                        alert(thrownError);
	                    }
	                });
	            },
	                "Não": function () {
	                $(this).dialog("close");
	            }
	        }
	    });
	});

   $("body").on("click", "#list-all-destination button.btn-info", function (e) {
	    e.returnValue = false;
	    var clickedID = this.id.split('-');
	    var destinationId = clickedID[1];
	    var url = "${pageContext.request.contextPath}/auth/editRequestedDestination/"+destinationId+"?${_csrf.parameterName}=${_csrf.token}";
	    
	    $.get(url,function(jsonData,status){
	    	
	    	var destinationName = jsonData.destination.idDestination;
	    	var arrive = jsonData.arrivalDate;
	    	var departure = jsonData.departureDate;
	    	var price = jsonData.valueNegotiated;
	    	var saleType = jsonData.saleType; 
	    	var observations = jsonData.negociationObservations;
	    	var ckb = jsonData.requestedDestination;
	    	
	    	var arriveFormated = $.format.date(arrive, "dd/MM/yyyy");
	    	var departureFormated = $.format.date(departure, "dd/MM/yyyy");
	    	
	 	    $("#edit-input-price").maskMoney(); 
		    $('#edit-input-arrive').mask('99/99/9999');
		    $('#edit-input-departure').mask('99/99/9999');
	    	
		    $('#destinationid-hidden').val(destinationName);
		    
    		$('#edit-input-departure').val(departureFormated);
    		$('#edit-input-arrive').val(arriveFormated);
    		$('#edit-input-price').val(price);
    		$('#edit-combo-saleType').val(saleType);
    		
    		$('#edit-destination-passenger-list').val(destinationName);
    		$('#edit-destination-passenger-list').attr('disabled', true);
    		
    		
    		$('#edit-destination-observations').val(observations);
    		$('#edit-ckb-requested').prop("checked", ckb);
    		
	      });

	});
   
   $('#destination-edit-form').submit( function(e) {
	   var destinationID = $('#destinationid-hidden').val();
	   
	   var url = "${pageContext.request.contextPath}/auth/updateDestinationRequested?${_csrf.parameterName}=${_csrf.token}";
	   
	   
	   var xxx = $('#destinationid-hidden').val();
	   var departure =  $('#edit-input-departure').val();
	   var arrive = $('#edit-input-arrive').val();
	   var price = $('#edit-input-price').val();
	   var saleType = $('#edit-combo-saleType').val();
	   var destinationId = $('#edit-destination-passenger-list').val();
	   var observations = $('#edit-destination-observations').val();
	   var ckb = $('#edit-ckb-requested').val();
	   
	    $.ajax({
	        url: url,
	        type: 'POST',
	        data:{
	        	id: xxx,
				departure: departure,
				arrive: arrive,
				price: price,
				saletype: saleType,
				destinationId: destinationId,
				observations: observations,
				ckb: ckb
			},
	        statusCode: {
	        	200: function(){
	        		$('#EditDestinationModal').modal('hide');
	        	}
	        }
	    });
	    e.preventDefault();
	});

</script>